package com.jnu.accounthelper.ui;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;

import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.AxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.jnu.accounthelper.MainActivity;
import com.jnu.accounthelper.R;
import com.jnu.accounthelper.db.Account;
import com.jnu.accounthelper.db.DBManager;
import com.jnu.accounthelper.ui.gallery.GalleryFragment;
import com.jnu.accounthelper.ui.slideshow.AccountFragment;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link LineChartFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class LineChartFragment extends Fragment {

    private LineChart mChart;
    private Spinner spinner;
    private List<Entry> entries;
    private RecyclerView recyclerView;
    private MyRecyclerViewAdapter adapter;
    private String s1="周";
    private ArrayList<Account> accounts=new ArrayList<>();
    private ArrayList<Account> show_accounts;
    private RadioGroup radioGroup;
    private LocalDate date;
    private int mode=1;

    public LineChartFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *

     * @return A new instance of fragment LineChart.
     */
    // TODO: Rename and change types and number of parameters
    public static LineChartFragment newInstance() {
        LineChartFragment fragment = new LineChartFragment();
        Bundle args = new Bundle();

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {

        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View root = inflater.inflate(R.layout.fragment_line_chart, container, false);
        recyclerView=root.findViewById(R.id.line_recycle);
        recyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));
        adapter = new MyRecyclerViewAdapter(accounts);
        recyclerView.setAdapter(adapter);

        mChart=root.findViewById(R.id.line_chart);
        mChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
                //Toast.makeText(LineChartFragment.this.getContext(),"点击了"+e.getX(), Toast.LENGTH_SHORT).show();
                if(s1.equals("周")){
                    if(date.getDayOfMonth()-e.getX()<1){
                        LocalDate localDate=date.minusDays((int)e.getX());
                        String day=date.getYear()+"年"+localDate.getMonth().getValue()+"月"+localDate.getDayOfMonth()+"日";
                        accounts=DBManager.SelectByDay(day,mode);
                        adapter.notifyDataSetChanged();
                    }
                    else {
                        String day=date.getYear()+"年"+date.getMonth().getValue()+"月"+(date.getDayOfMonth()-(int)e.getX())+"日";
                        accounts=DBManager.SelectByDay(day,mode);
                        adapter.notifyDataSetChanged();
                    }
                }
                else {
                    if(date.getMonth().getValue()-e.getX()<1){
                        LocalDate localDate=date.minusMonths((int)e.getX());
                        accounts=DBManager.SelectByMonth(localDate.getYear(),localDate.getMonth().getValue(),mode);
                        adapter.notifyDataSetChanged();
                    }
                    else {
                        accounts=DBManager.SelectByMonth(date.getYear(),date.getMonth().getValue()-(int)e.getX(),mode);
                        adapter.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void onNothingSelected() {

            }
        });
        spinner=root.findViewById(R.id.item_spinner);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mode = position+1;
                setChart();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        radioGroup=root.findViewById(R.id.radio_group2);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                int radioButtonId = group.getCheckedRadioButtonId();
                RadioButton rb = (RadioButton)root.findViewById(radioButtonId);
                s1=rb.getText().toString();
                setChart();
            }
        });
        date = LocalDate.now();

        setChart();

        return root;
    }
    float sumUp(List<Account> accounts){
        float sum=0;
        for(Account account:accounts){
            sum+=account.getNumber();
        }
        if(sum<0) return -1*sum;
        else return sum;
    }
    @RequiresApi(api = Build.VERSION_CODES.O)
    void setData(){
        entries=new ArrayList<>();

            if(s1.equals("周")){
                for(int i=0;i<7;i++){
                    entries.add(new Entry(i,sumUp(DBManager.SelectByDay(date.getYear(),date.getMonth().getValue(),date.getDayOfMonth()-i,mode))));
                }
            }
            else if(s1.equals("月")) {
                for (int i = 0; i < 12; i++) {
                    entries.add(new Entry(i,sumUp(DBManager.SelectByMonth(date.getYear(),date.getMonth().getValue()-i,mode))));
                }
            }


    }
    @RequiresApi(api = Build.VERSION_CODES.O)
    void setChart(){
        setData();
        LineDataSet dataSet=new LineDataSet(entries,"");
        dataSet.setColor(Color.parseColor("#000000"));
        dataSet.setCircleColor(Color.parseColor("#000000"));
        dataSet.setCircleRadius(6f);
        dataSet.setLineWidth(1.5f);
        dataSet.setValueTextColor(Color.parseColor("#000000"));
        dataSet.setValueTextSize(17f);
        YAxis yAxis=mChart.getAxisRight();
        yAxis.setEnabled(false);
        XAxis xAxis=mChart.getXAxis();
        xAxis.setTextColor(Color.RED);
        xAxis.setTextSize(9f);
        xAxis.setDrawAxisLine(true);
        xAxis.setDrawLabels(true);
        xAxis.setDrawGridLines(false);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setValueFormatter(new AxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                if(s1.equals("周")){
                    if(date.getDayOfMonth()-value<1){
                        LocalDate localDate=date.minusDays((int)value);
                        return (int)localDate.getMonth().getValue()+"月"+(int)localDate.getDayOfMonth()+"日";
                    }
                    else return (int)date.getMonth().getValue()+"月"+(int)(date.getDayOfMonth()-value)+"日";
                }
                else {
                    if(date.getMonth().getValue()-value<1){
                        LocalDate localDate=date.minusMonths((int)value);
                        return localDate.getYear()+"年"+(int)localDate.getMonth().getValue()+"月";
                    }
                    else return date.getYear()+"年"+(int)(date.getMonth().getValue()-value)+"月";
                }
            }

            @Override
            public int getDecimalDigits() {
                return 0;
            }
        });
        Legend legend=mChart.getLegend();
        legend.setForm(Legend.LegendForm.LINE);
        legend.setTextSize(15f);
        legend.setFormSize(15f);
        legend.setTextColor(Color.BLUE);
        LineData lineData=new LineData(dataSet);
        mChart.setData(lineData);
        mChart.invalidate();
    }
    private class MyRecyclerViewAdapter extends RecyclerView.Adapter{
        //private List<Account> accounts;


        public MyRecyclerViewAdapter(List<Account> accounts) {
            //this.accounts=accounts;
        }
        @NonNull
        //加载视图
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view;
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.account_item_holder, parent, false);
            return new MyRecyclerViewAdapter.MyViewHolder(view);


        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder Holder, int position) {
            MyRecyclerViewAdapter.MyViewHolder holder =(MyRecyclerViewAdapter.MyViewHolder)Holder;
            holder.getImageView().setImageResource(accounts.get(position).getCoverResourceId());
            holder.getType().setText(accounts.get(position).getType());
            holder.getNumber().setText(accounts.get(position).getNumber()+"");
            holder.getRemark().setText(accounts.get(position).getRemark());
            holder.getDate().setText(accounts.get(position).getDate());
        }



        @Override
        public int getItemCount() {
            return accounts.size();
        }

        private class MyViewHolder extends RecyclerView.ViewHolder{

            private final ImageView imageView;
            private final TextView type;
            private final TextView remark;
            private final TextView number;
            private final TextView date;

            public MyViewHolder(View view) {
                super(view);

                this.imageView=view.findViewById(R.id.image_view_book_cover);
                this.type=view.findViewById(R.id.type);
                this.remark=view.findViewById(R.id.remark);
                this.number=view.findViewById(R.id.number);
                this.date=view.findViewById(R.id.item_date);

            }
            public TextView getDate() {
                return date;
            }

            public ImageView getImageView() {
                return imageView;
            }

            public TextView getType() {
                return type;
            }

            public TextView getRemark() {
                return remark;
            }

            public TextView getNumber() {
                return number;
            }


        }
    }
}